// @ts-check
import { createSlice, combineReducers, configureStore } from '@reduxjs/toolkit';
import createSagaMiddleware from 'redux-saga';
import mySaga from './saga';

const todo = createSlice({
  name: 'todoList',
  initialState: [
    { text: 'firstTodo', completed: true },
    { text: 'secondTodo', completed: false },
  ],
  reducers: {
    add: (state, { payload }) => {
      return [...state, { text: payload, completed: false }];
    },
    toggle: (state, { payload }) => {
      return state.map((ele, i) => (i === payload ? { ...ele, completed: !ele.completed } : ele));
    },
  },
});

const filter = createSlice({
  name: 'filter',
  initialState: 'all', // all , completed, uncompleted
  reducers: {
    setFilter: (state, { payload }) => {
      return ['all', 'completed', 'uncompleted'].includes(payload) ? payload : state;
    },
  },
});

const reducer = combineReducers({ todoList: todo.reducer, filter: filter.reducer });

const sagaMiddleware = createSagaMiddleware();

const store = configureStore({
  reducer,
  middleware: (getDefaultMiddleware) => {
    const list = getDefaultMiddleware(); // 非生产模式返回3个，生产模式返回的只有thunk
    return list.concat(sagaMiddleware);
  },
});

export default store;

export const actions = { ...todo.actions, ...filter.actions };

sagaMiddleware.run(mySaga);
